package cn.imvc.app.models;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Goods;
import cn.imvc.app.entities.GoodsAttrValue;
import cn.imvc.app.entities.GoodsSku;
import cn.imvc.app.entities.GoodsTypeValue;
import cn.imvc.app.entities.UserSeller;
import cn.imvc.app.repositories.GoodsRepository;
import cn.imvc.app.repositories.GoodsSkuRepository;
import cn.imvc.core.ICache;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;

@Service
public class GoodsModelImpl implements GoodsModel {

	@Autowired
	GoodsRepository goodsRepository;
	@Autowired
	GoodsSkuModel goodsSkuModel;
	@Autowired
	GoodsPriceModel goodsPriceModel; 
	@Autowired
	GoodsReviewsModel goodsReviewsModel;
	@Autowired
	ICache cache;
	@Autowired
	GoodsClassModel goodsClassModel;
	@Autowired
	RefRelationModel refRelationModel;
	@Autowired
	BrandGoodsClassModel brandGoodsClassModel;
	@Autowired
	GoodsClassAttrModel goodsClassAttrModel;
	@Autowired
	UserSellerModel userSellerModel;
	
	public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestMap() {
		// TODO Auto-generated method stub
		return null;
	}

	public Page<Goods> find(ViewRequest viewRequest) {
		if(viewRequest == null){
			viewRequest=new ViewRequest();
		}
		List<UserSeller> userSellers = userSellerModel.getUserSellersByCurUser();
		if(!userSellers.isEmpty()){
			String pre = " and ";
			if(viewRequest.getParams() == null){
				viewRequest.setParams(new HashMap<>());
				pre = "";
			}
			Iterator<UserSeller> iterator = userSellers.iterator();
			StringBuffer sb = new StringBuffer();
			while (iterator.hasNext()) {
				UserSeller userSeller = (UserSeller) iterator.next();
				sb.append(userSeller.getSeller().getId());
				if(iterator.hasNext()){
					sb.append(",");
				}
			}
			viewRequest.getParams().put(pre+" g.seller.id in ("+sb.toString()+") ", " and g.id != -1");
		}
		viewRequest.getSort().put("g.editTime", "desc");
		return goodsRepository.findAll("g","Goods g",ModelUtil.OrderByIdDesc(viewRequest));
	}

	public Goods get(int id) {
		return goodsRepository.findOne(id);
	}

	public Goods save(Goods goods) {
		goods.setAddTime(new Date());
		goods.setEditTime(new Date());
		goods.setVerify((byte)10);
		String detail = goods.getDetail() == null ? "" : goods.getDetail();
		goods.setDetail(detail.replace("<p><br/></p>", ""));
		goods.setClassStr(goodsClassModel.getClassPathStr(goods.getGoodsClass().getId()));
//		//更新品牌类别关联表的信息，需放在保存商品前
//		brandGoodsClassModel.updateRelation(goods,1);
//		//更新类别属性关联表的信息，需放在保存商品前
//		goodsClassAttrModel.updateRelationByGoods(goods,1);
		Goods goodsTmp = null;
		if(goods.getState() == 0){
			//如果改为下架，商品将将直接下架，不需要审核
			goods.setVerify((byte)1);
			goodsTmp = goodsRepository.saveAndFlush(goods);
			//将sku也下线
			goodsSkuModel.updateSkuState(goodsTmp);
		}else{
			goods.setState((byte)(goods.getState()+10));
			goodsTmp = goodsRepository.saveAndFlush(goods);
			goodsReviewsModel.saveReviews(goodsTmp);
		}
		cache.removeSecond("MAX_ID", "goods");
		return goodsTmp;
	}
	
	//该方法弃用，改用updateProperties
	@Deprecated
	public Goods update(Goods goods) {
		if(goods.getState() == 0){
			goodsRepository.saveAndFlush(goods);
		}else{
			goods.setState((byte)0);
			goodsRepository.saveAndFlush(goods);
			goodsReviewsModel.saveReviews(goods);
		}
		return goods;
	}

	public Goods updateProperties(Goods goods,boolean isReview) {
		Goods goodsTmp=get(goods.getId());
		List<GoodsSku> goodsSkus = goodsSkuModel.findByGoods(goods);
		Iterator<GoodsSku> iterator = goodsSkus.iterator();
		int sumInventory = 0;
		int sumCollect = 0;
		int sumSale = 0;
		int sumClick = 0;
		while (iterator.hasNext()) {
			GoodsSku goodsSku = (GoodsSku) iterator.next();
			if(goodsSku.getState() != (byte)0){
				sumInventory += goodsSku.getInventory() == null ? 0 : goodsSku.getInventory();
				sumCollect += goodsSku.getCollect() == null ? 0 : goodsSku.getCollect();
				sumSale += goodsSku.getSalenum() == null ? 0 : goodsSku.getSalenum();
				sumClick += goodsSku.getClick() == null ? 0 : goodsSku.getClick();
			}
		}
		goods.setClick(sumClick);
		goods.setSalenum(sumSale);
		goods.setCollect(sumCollect);
		goods.setInventory(sumInventory);
		goods.setEditTime(new Date());
		goods.setPrice(goodsTmp.getPrice());
		goods.setPrice2(goodsTmp.getPrice2());
		goods.setAttrStr(goodsTmp.getAttrStr());
		goods.setTypeStr(goodsTmp.getTypeStr());
		goods.setEvaluationCount(goodsTmp.getEvaluationCount());
		goods.setVerifyRemark(goodsTmp.getVerifyRemark());
		goods.setClassStr(goodsClassModel.getClassPathStr(goods.getGoodsClass().getId()));
		String detail = goods.getDetail() == null ? "" : goods.getDetail();
		goods.setDetail(detail.replace("<p><br/></p>", ""));
		goods.setVersion(goodsTmp.getVersion());
//		//更新品牌类别关联表的信息，需放在保存商品前
//		brandGoodsClassModel.updateRelation(goods,1);
//		//更新类别属性关联表的信息，需放在保存商品前
//		goodsClassAttrModel.updateRelationByGoods(goods,1);
//		goodsTmp = goodsRepository.saveAndFlush(goods);
//		goodsReviewsModel.saveReviews(goodsTmp);
		if(isReview){
			if(goods.getState() == 0){
				//如果改为下架，商品将将直接下架，不需要审核
				goods.setVerify((byte)1);
				goodsTmp = goodsRepository.saveAndFlush(goods);
			}else{
//				goods.setState((byte)0);
				goods.setVerify((byte)10);
				if(goods.getState() == 1 || goods.getState() == 3){
					goods.setState((byte)(goods.getState()+10));
				}
				goodsTmp = goodsRepository.saveAndFlush(goods);
				goodsReviewsModel.saveReviews(goodsTmp);
			}
			//同步sku状态
			goodsSkuModel.updateSkuState(goodsTmp);
		}else{
//			goods.setVerify((byte)1);
			//如果没有个一正常的sku或赠品，则将该商品也下架
			byte[] bytes = {1,11,3,13};
			if(goodsRepository.getGoodsSkuCountBySkuStates(bytes, goods.getId()) == 0){
				goods.setState((byte)0);
			}
			goodsTmp = goodsRepository.saveAndFlush(goods);
			goodsPriceModel.updateGoodsLowPrice(goodsTmp.getId());
			goodsTmp = goodsRepository.getOne(goodsTmp.getId());
		}
		cache.removeSecond("MAX_ID", "goods");
		return goodsTmp;
	}

	public String delete(int id) {
		String result = refRelationModel.deleteDateCheck("Goods", "id", id);
		if(result.equals("")){
			Goods goods = get(id);
//			//更新品牌类别关联表的信息，需放在保存商品前
//			brandGoodsClassModel.updateRelation(goods,0);
//			//更新类别属性关联表的信息，需放在保存商品前
//			goodsClassAttrModel.updateRelationByGoods(goods,0);
			goodsPriceModel.deleteByGoods(goods);
			goodsSkuModel.deleteByGoods(goods);
			goodsRepository.delete(id);
			cache.removeSecond("MAX_ID", "goods");
			return "";
		}else{
			return result;
		}
	}

	public String deleteBatch(int[] ids) {
		for (int id : ids) {
			String result = delete(id);
			if(!result.equals("")){
				return result;
			}
		}
		return "";
	}

	public Goods updateVerify(Goods goods) {
		return goodsRepository.saveAndFlush(goods);
	}

	/**
	 * 更新商品属性
	 */
	public void updateGoodsAttr(int goodsId, List<GoodsAttrValue> goodsAttrValues) {
		Iterator<GoodsAttrValue> iterator = goodsAttrValues.iterator();
		StringBuffer stringBuffer = new StringBuffer();
		while (iterator.hasNext()) {
			GoodsAttrValue goodsAttrValue = (GoodsAttrValue) iterator.next();
			if(goodsAttrValue.getAttrValue() == null){
				continue;
			}
//			stringBuffer.append(goodsAttrValue.getAttrClass().getId()+"_"+goodsAttrValue.getAttrValue().getId());
			stringBuffer.append(goodsAttrValue.getAttrValue().getId());
			if(iterator.hasNext()){
				stringBuffer.append(" ");
			}
		}
		Goods goodsTmp = get(goodsId);
		goodsTmp.setAttrStr(stringBuffer.toString());
		goodsRepository.saveAndFlush(goodsTmp);
	}
	
	/**
	 * 更新商品类型
	 */
	public void updateGoodsType(int goodsId, List<GoodsTypeValue> goodsTypeValues) {
		Iterator<GoodsTypeValue> iterator = goodsTypeValues.iterator();
		StringBuffer stringBuffer = new StringBuffer();
		while (iterator.hasNext()) {
			GoodsTypeValue goodsTypeValue = (GoodsTypeValue) iterator.next();
			if(goodsTypeValue.getTypeValue() == null){
				continue;
			}
//			stringBuffer.append(goodsTypeValue.getTypeClass().getId()+"_"+goodsTypeValue.getTypeValue().getId());
			stringBuffer.append(goodsTypeValue.getTypeValue().getId());
			if(iterator.hasNext()){
				stringBuffer.append(" ");
			}
		}
		Goods goodsTmp = get(goodsId);
		goodsTmp.setTypeStr(stringBuffer.toString());
		goodsRepository.saveAndFlush(goodsTmp);
	}
	
	/**
	 * 更新评论
	 */
	public void updateComments(int goodsId) {
		Goods goods = get(goodsId);
		goods.setEvaluationCount(goods.getEvaluationCount()+1);
		goodsRepository.saveAndFlush(goods);
	}
	
	/**
	 * v0.1当已存在sku，而商品规格变化时，将商品下架，封存所有sku。
	
	public void updateAfterSpecChange(int goodsId){
		//封存所有sku
		goodsSkuModel.updateMothballAll(goodsId);
		Goods goods = get(goodsId);
		goods.setEditTime(new Date());
		goods.setVerify((byte)10);
		goods.setState((byte)0);
		Goods goodsTmp = goodsRepository.saveAndFlush(goods);
		goodsReviewsModel.saveReviews(goodsTmp);
	} 
	*/
	
	/**
	 * v0.2当商品规格变化时，将商品下架，重新审核。
	 */
	public void updateAfterSpecChange(int goodsId){
		Goods goods = get(goodsId);
		goods.setEditTime(new Date());
		if(goods.getState() == 1 || goods.getState() == 3){
			goods.setVerify((byte)10);
//			goods.setState((byte)0);
			goods.setState((byte)(goods.getState()+10));
			Goods goodsTmp = goodsRepository.saveAndFlush(goods);
			goodsReviewsModel.saveReviews(goodsTmp);
		}else{
			Goods goodsTmp = goodsRepository.saveAndFlush(goods);
		}
	}
}
